<?php

/**
 *
 * @author lovebing <lovebing365@126.com> Created on 2014-10-1 20:44:48
 */
class BaseConsoleCommand extends CConsoleCommand {

    private $args = '';

    public function init() {
        parent::init();
        umask(000);
        set_time_limit(0);
        Yii::app()->attachEventHandler('onError', array($this, 'handelError'));
        Yii::app()->attachEventHandler('onException', array($this, 'handelException'));
    }

    public function handelError(CEvent $event) {
        $this->abort($event->message, $event->code);
    }

    public function handelException(CEvent $event) {
       // $this->abort($event->exception->getMessage(), $event->exception->getCode());
    }

    public function run($args) {
        $this->args = $args;

        if ($this->isLocked()) {
            $this->forbid("DO NOT run repeatedly.\n");
        }
        parent::run($args);
    }

    public function lock() {
        return file_put_contents($this->getLockFullPath(), '') !== false;
    }

    public function unlock() {
        $file = $this->getLockFullPath();
        if (!is_file($file)) {
            return true;
        }
        return unlink($file);
    }

    public function isLocked() {
        return is_file($this->getLockFullPath());
    }

    public function getLockFullPath() {
        $lockDir = Yii::app()->getRuntimePath() . '/lock';
        if (!is_dir($lockDir)) {
            mkdir($lockDir);
        }
        return $lockDir . '/' . $this->getLockName() . '.lock';
    }

    public function getActionName() {
        list($action, $options, $args) = $this->resolveRequest($this->args);
        return $action;
    }

    public function getArgs() {
        return $this->getArgs();
    }

    public function getLockName() {
        return $this->getName() . '.' . $this->getActionName();
    }

    public function abort($msg = '', $status = 1) {
        $this->unlock();
        $this->forbid($msg, $status);
    }

    public function forbid($msg = '', $status = 1) {
        echo $msg;
        Yii::app()->end($status);
    }

    public function getViewPath() {
        return Yii::app()->getBasePath() . '/views';
    }

    public function __destruct() {
        
    }

    public function getYiicPath() {
        return Yii::app()->getBasePath() . '/yiic';
    }

    public function exec($yiicommand) {
        $command = $this->getYiicPath() . '  ' . $yiicommand . ' &';
        exec($command);
    }

}
